package com.atguigu.bigdata.spark.zzgcore.rdd.operator.transform

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

import java.text.SimpleDateFormat
import java.util.Date

/**
 * @Classname Spark01_RDD_Operation_Transfrom
 * @Description 相同的首字母放在一个组中
 * @Date 2023/9/20 15:23
 * @Author zhuzhenguo
 */
object Spark06_RDD_Operation_Transform_Test {
  def main(args: Array[String]): Unit = {
    // 准备环境,这个 *表示系统当前最大可用核数
    val sparkConf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("Operator")
    val sc = new SparkContext(sparkConf)
    val rdd: RDD[String] = sc.textFile("datas/apache.log")
    // timeRDD => (hour, (hour,1))
    // Iterable[(String, Int)]相同的时间所形成的集合
    val timeRDD: RDD[(String, Iterable[(String, Int)])] = rdd.map(
      line => {
        val datas: Array[String] = line.split(" ")
        val time: String = datas(3)
        val sdf = new SimpleDateFormat("dd/MM/yyyy:HH:mm:ss")
        val date: Date = sdf.parse(time)
        val sdf1 = new SimpleDateFormat("HH")
        val hour: String = sdf1.format(date)
        // 每来一行出现一次
        (hour, 1)
      }
    ).groupBy(_._1)

    // 模式匹配 (偏函数)
    timeRDD.map {
      case (hour, iter) => {
        (hour, iter.size)
      }
    }.collect.foreach(println)

    // 关闭环境
    sc.stop()
  }
}
